package com.example.nutritionmanager.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.api.RecordService
import com.example.nutritionmanager.bodys.responseBodys.DailyNutritionResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed class RecordState {
    object Idle : RecordState()
    object Loading : RecordState()
    data class Success(val response: DailyNutritionResponse) : RecordState()
    data class Error(val error: String) : RecordState()
}

@HiltViewModel
class RecordViewModel @Inject constructor(
    private val recordService: RecordService
) : ViewModel() {

    private val _recordState = MutableStateFlow<RecordState>(RecordState.Idle)
    val recordState = _recordState.asStateFlow()

    /**
     * 获取指定日期的营养记录
     */
    fun fetchRecordsByDate(date: String) {
        viewModelScope.launch {
            _recordState.value = RecordState.Loading
            try {
                val response = recordService.getDayMealsRecord(date)
                if (response.isSuccessful) {
                    val dailyResponse = response.body()
                    if (dailyResponse != null) {
                        _recordState.value = RecordState.Success(dailyResponse)
                    } else {
                        _recordState.value = RecordState.Error("返回数据为空")
                    }
                } else {
                    _recordState.value = RecordState.Error("获取记录失败：${response.code()}")
                }
            } catch (e: Exception) {
                _recordState.value = RecordState.Error("网络错误：${e.localizedMessage}")
            }
        }
    }

    /**
     * 重置状态
     */
    fun resetState() {
        _recordState.value = RecordState.Idle
    }
}